package github.saw96x.remoting.transport.socket;

import github.saw96x.common.factory.SingletonFactory;
import github.saw96x.remoting.handler.RpcRequestHandler;
import github.saw96x.remoting.pojo.RpcRequest;
import github.saw96x.remoting.pojo.RpcResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author Saw96x
 * @date 2022/3/18 20:50
 */
@Slf4j
public class SocketRpcRequestHandlerRunnable implements Runnable {
  private final Socket socket;
  private final RpcRequestHandler rpcRequestHandler;


  public SocketRpcRequestHandlerRunnable(Socket socket) {
    this.socket = socket;
    this.rpcRequestHandler = SingletonFactory.getInstance(RpcRequestHandler.class);
  }

  @Override
  public void run() {
    log.info("server handle message from client by thread: [{}]", Thread.currentThread().getName());
    try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
         ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) {
      RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();
      Object result = rpcRequestHandler.handle(rpcRequest);
      objectOutputStream.writeObject(RpcResponse.success(result, rpcRequest.getRequestId()));
      objectOutputStream.flush();
    } catch (IOException | ClassNotFoundException e) {
      log.error("occur exception:", e);
    }
  }

}
